<script setup lang="ts">
defineOptions({
  name: "GAS_OPERATION_BOTTLEMANAGE_REPLACEBOTTLE_ADDORDER"
});
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { PxMessage } from "px-ui";
import { ArrowLeft } from "@px-ui/icons-vue";
import ReTeleport from "@/components/ReTeleport";
import ReCollapse from "@/components/ReCollapse";
import baseInfo from "./components/baseInfo.vue";
import baseInfoTable from "./components/baseInfoTable.vue";
import checkList from "./components/checkList.vue";
import {
  submitGasOrder,
  saveGasDraftOrder,
  queryGasChecklist,
  queryGasOrderDetail,
  saveGasOrderExecute,
  submitGasOrderExecute
} from "@/api/modules/operation";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import { loadingTimeout } from "@/utils/http/constant";

const route = useRoute();
const router = useRouter();

const addArguments: Record<string, any> = {
  // 任务类型(1：气瓶， 2：酸桶)
  taskType: 1,
  // 内容模板id 由 checkList 带出
  templateId: 0
};

const baseInfoRef = ref<InstanceType<typeof baseInfo> | null>(null);
const baseInfoTableRef = ref<InstanceType<typeof baseInfoTable> | null>(null);
const checkListRef = ref<InstanceType<typeof checkList> | null>(null);
const checkListCollapseValue = ref<string>("");
const gasOrderDetailOriginData = ref<Record<string, any>>(null);
const gasOrderDetailData = ref<Record<string, any>>({
  workOrderNo: "",
  location: "",
  deviceCode: "",
  executor: "",
  executorName: "",
  startTime: "",
  endTime: "",
  createRemark: ""
});
const checkListDataList = ref<Array<Record<string, any>>>([]);
const isAxiosDataOK = ref<boolean>(false);
const loading = ref<boolean>(false);

const isShowReTeleport = computed(() => !route.query.type);
const isShowBaseInfo = computed(() => !route.query.type);
// status   1 执行中    2 执行完成
const checkListDisabled = computed(() => route.query.type !== "edit" || route.query.status !== "1");
const btnDisabled = computed(() => !checkListDataList.value?.length);

const baseInfoChangeHandler = async (ag: any, form: any) => {
  const { gasName = "" } = ag;
  if (gasName) {
    await queryGasChecklistFn(gasName);
  } else {
    checkListDataList.value = [];
  }
};

const cancelHandler = () => {
  const path = "/gas/operation/bottleManage/replaceBottle";
  router.push({ path });
};

/**
 * @description: 获取工单基本信息参数
 * @return {*}
 */
const getOrderParams = async (id?: string) => {
  const form: Record<string, any> | null = await baseInfoRef.value.validate();
  if (!form) return null;
  // taskType  任务类型(1：气瓶， 2：酸桶)
  // templateId  内容模板id 由 checkList 带出
  const { taskType = 1, templateId = 0 } = addArguments;
  if (id) {
    return { ...form, taskType, id };
  } else {
    return { ...form, taskType, templateId };
  }
};

/**
 * @description: 获取工单执行参数
 * @return {*}
 */
const getOrderExecuteParams = async (flag = false) => {
  const {
    query: { id = "" }
  } = route;
  // 1:气瓶 2：酸桶 3:槽车充装
  const taskType = 1;
  let subTaskDTO = null;
  if (flag) {
    subTaskDTO = await checkListRef.value.validate();
  } else {
    subTaskDTO = checkListRef.value.getParams();
  }
  return { id, taskType, subTaskDTO };
};
/**
 * @description: 保存为工单草稿
 * @return {*}
 */
const saveGasOrderFn = async (id?: string) => {
  let params = null;
  if (id) {
    params = await getOrderParams(id);
    if (!params) return;
  } else {
    params = baseInfoRef.value.baseInfoRuleForm;
  }
  loading.value = true;
  const res = await saveGasDraftOrder(params, () => {
    loading.value = false;
  });
  loading.value = false;
  if (!res) return;
  PxMessage.success("保存成功！");
};
/**
 * @description: 保存为执行草稿
 * @return {*}
 */
const saveGasOrderExecuteFn = async () => {
  const params = await getOrderExecuteParams();
  if (!params) return;
  loading.value = true;
  const res = await saveGasOrderExecute(params, () => {
    loading.value = false;
  });
  loading.value = false;
  if (!res) return;
  PxMessage.success("保存成功！");
};
/**
 * @description: 保存事件
 * @param {*} useThrottleFn
 * @return {*}
 */
const saveHandler = useThrottleFn(async () => {
  const {
    query: { type = "add" }
  } = route;
  if (type === "add") {
    await saveGasOrderFn();
  }
  if (type === "edit") {
    await saveGasOrderExecuteFn();
  }
  const path = "/gas/operation/bottleManage/replaceBottle";
  router.push({ path });
}, delay);

/**
 * @description: 提交为工单（创建工单）
 * @return {*}
 */
const submitGasOrderFn = async () => {
  const params = await getOrderParams();
  if (!params) return;
  loading.value = true;
  const r = await submitGasOrder(params, () => {
    loading.value = false;
  });
  loading.value = false;
  if (!r) return;
  PxMessage.success("创建成功！");
};

/**
 * @description: 提交工单执行结果
 * @return {*}
 */
const submitGasOrderExecuteFn = async () => {
  const params = await getOrderExecuteParams(true);
  if (!params) return;
  loading.value = true;
  const res = await submitGasOrderExecute(params, () => {
    loading.value = false;
  });
  loading.value = false;
  if (!res) return;
  PxMessage.success("保存成功！");
};
/**
 * @description: 提交事件
 * @param {*} useThrottleFn
 * @return {*}
 */
const submitHandler = useThrottleFn(async () => {
  const {
    query: { type = "add" }
  } = route;
  if (type === "add") {
    await submitGasOrderFn();
  }
  if (type === "edit") {
    await submitGasOrderExecuteFn();
  }
  const path = "/gas/operation/bottleManage/replaceBottle";
  router.push({ path });
}, delay);

/**
 * @description: 获取工单详情
 * @return {*}
 */
const queryGasOrderDetailFn = async () => {
  loading.value = true;
  const {
    query: { id = "" }
  } = route;
  const res = await queryGasOrderDetail({ id }, () => {
    loading.value = false;
  });
  if (res) {
    gasOrderDetailOriginData.value = res;
    const {
      workOrderNo = "",
      location = "",
      deviceCode = "",
      executor = "",
      executorName = "",
      startTime = "",
      endTime = "",
      createRemark = "",
      subTaskDTOList = []
    } = res;
    gasOrderDetailData.value.workOrderNo = workOrderNo;
    gasOrderDetailData.value.location = location;
    gasOrderDetailData.value.deviceCode = deviceCode;
    gasOrderDetailData.value.executor = executor;
    gasOrderDetailData.value.executorName = executorName;
    gasOrderDetailData.value.startTime = startTime;
    gasOrderDetailData.value.endTime = endTime;
    gasOrderDetailData.value.createRemark = createRemark;
    checkListDataList.value.splice(0);
    let lastExecutor = "";
    let firstEmptyTitle = "";
    checkListDataList.value = subTaskDTOList?.map((item, index) => {
      const { executor = "", subTaskTypeDesc = "", taskChecklistResult = [] } = item;
      item["title"] = subTaskTypeDesc;
      item["isLast"] = index === subTaskDTOList.length - 1;
      item["isLastExecutor"] = false;
      if (executor) {
        lastExecutor = executor;
        if (item["isLast"]) {
          item["isLastExecutor"] = true;
        } else {
          const { executor: nextExecutor = "" } = subTaskDTOList[index + 1];
          if (!nextExecutor) {
            item["isLastExecutor"] = true;
          }
        }
      }
      item["firstEmptyTitle"] = "";
      if (lastExecutor && !executor && !item["isLastExecutor"] && !firstEmptyTitle) {
        firstEmptyTitle = subTaskTypeDesc;
        item["firstEmptyTitle"] = subTaskTypeDesc;
      }
      item["data"] = taskChecklistResult?.map(ite => {
        const { id, content, result, remark } = ite;
        let status = "";
        if (result) {
          if (result === "Y" || result === "N") {
            status = result;
          } else {
            status = "o";
          }
        } else {
          status = "o";
        }
        return { id, content, result, remark, status };
      });
      return item;
    });
    // 第一次执行时
    if (!firstEmptyTitle) {
      checkListDataList.value[0].firstEmptyTitle = checkListDataList.value[0].subTaskTypeDesc;
    }
    checkListCollapseValue.value = subTaskDTOList?.reduce((pre, cur, index, arr) => {
      const { executor = null, subTaskTypeDesc = "" } = cur;
      if (!executor && !pre) {
        pre = subTaskTypeDesc;
      }
      if (index === arr.length - 1 && !pre) {
        pre = arr[0]?.subTaskTypeDesc;
      }
      return pre;
    }, "");
  }
  loading.value = false;
};

/**
 * @description: 获取checklist表单（空白表）
 * @return {*}
 */
const queryGasChecklistFn = async (gasName: string = "") => {
  checkListDataList.value.splice(0);
  if (!gasName) return;
  // taskType 任务类型 (1-气瓶,2-酸桶,3-槽车充填)
  const taskType = 1;
  const params = { gasName, taskType };
  const res = await queryGasChecklist(params);
  if (!res.length) return;
  const ar = res.map(item => {
    const { contentList, templateId, title } = item;
    addArguments.templateId = templateId;
    const id = "";
    const contentId = "";
    const status = "";
    const result = "";
    const remark = "";
    const data = contentList.map(content => ({ id, contentId, content, status, result, remark }));
    return { title, data };
  });
  checkListDataList.value.push(...ar);
  checkListCollapseValue.value = ar[0]?.title;
};

const submitCheckListItemHandler = (index: number) => {
  const userInfo = localStorage.getItem("userInfo");
  const { userId = null } = JSON.parse(userInfo);
  const editedIndex = checkListDataList.value.findIndex(item => item.isLastExecutor);
  if (editedIndex > -1) {
    if (editedIndex !== index && editedIndex < index) {
      checkListDataList.value[editedIndex].isLastExecutor = false;
      checkListDataList.value[index].isLastExecutor = true;
      checkListDataList.value[index].executor = userId;
      checkListDataList.value[index].firstEmptyTitle = "";
      if (!checkListDataList.value[index].isLast) {
        checkListDataList.value[index + 1].firstEmptyTitle = checkListDataList.value[index + 1].subTaskTypeDesc;
      }
    }
  } else {
    checkListDataList.value[index].isLastExecutor = true;
    checkListDataList.value[index].executor = userId;
    checkListDataList.value[index].firstEmptyTitle = "";
    checkListDataList.value[index + 1].firstEmptyTitle = checkListDataList.value[index + 1].subTaskTypeDesc;
  }
};

const init = async () => {
  setTimeout(() => {
    isAxiosDataOK.value = true;
  }, loadingTimeout);
  const {
    query: { type = "add" }
  } = route;
  const flag_1 = type === "check" || type === "edit";
  flag_1 && (await queryGasOrderDetailFn());
  isAxiosDataOK.value = true;
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <div v-loading="loading" class="replace-bottle-add">
    <div class="add-btn">
      <px-button type="primary" :icon="ArrowLeft" @click="cancelHandler">返回</px-button>
    </div>
    <div class="add-content">
      <ReCollapse v-if="isShowBaseInfo" title="基础信息">
        <baseInfo ref="baseInfoRef" v-model="gasOrderDetailData" @change="baseInfoChangeHandler" />
      </ReCollapse>
      <div v-else-if="isAxiosDataOK" class="content-execute">
        <div class="content-execute-title">
          <div class="title-text">基础信息</div>
        </div>
        <baseInfoTable ref="baseInfoTableRef" :data="gasOrderDetailOriginData" />
      </div>
      <ReCollapse v-if="isShowBaseInfo" title="CheckList">
        <checkList v-if="isAxiosDataOK" ref="checkListRef" v-model="checkListCollapseValue" :disabled="checkListDisabled" :data="checkListDataList" />
      </ReCollapse>

      <div v-else-if="isAxiosDataOK" class="content-execute">
        <div class="content-execute-title">
          <div class="title-text">CheckList</div>
        </div>
        <checkList
          v-if="isAxiosDataOK"
          ref="checkListRef"
          v-model="checkListCollapseValue"
          :disabled="checkListDisabled"
          :data="checkListDataList"
          @submit="submitCheckListItemHandler"
        />
      </div>
    </div>
    <ReTeleport v-if="isShowReTeleport">
      <div class="replace-bottle-add-teleport-btns">
        <px-button type="info" @click="cancelHandler">取消</px-button>
        <px-button v-if="route.query.status" type="primary" :disabled="btnDisabled" plain @click="saveHandler">保存为草稿</px-button>
        <px-button type="primary" :disabled="btnDisabled" @click="submitHandler">提交</px-button>
      </div>
    </ReTeleport>
  </div>
</template>

<style lang="scss" global>
.replace-bottle-add-teleport-btns {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 100%;
  padding: 16px;
}
</style>
<style lang="scss" scoped>
.replace-bottle-add {
  box-sizing: border-box;
  padding: 16px;
  background-color: #fff;

  .add-content {
    display: flex;
    flex-direction: column;
    gap: 16px;
    margin-top: 16px;

    .re-collapse-title-slot {
      .px-form-item {
        margin-bottom: 0;

        .px-input {
          width: 300px;
        }
      }
    }

    .content-execute {
      .content-execute-title {
        .title-text {
          height: 40px;
          font-weight: 600;
          line-height: 40px;
          color: #555;
        }
      }

      .participator {
        .form {
          .px-form-item {
            .px-input {
              width: 300px;
            }
          }
        }
      }
    }
  }
}
</style>
